<?php

include_once('../../index.php');
include_once('templates/core/Smarty.class.php');
$smarty = new smarty();

$isCookied = isset($_COOKIE['identify'], $_COOKIE['hash']);
$isReceiveForm = count($_POST) > 0;
$isIdentify = false;
$message = '';

//The user send correctly indentify and hash
if (!$isCookied) {
  // This step is for when type directly /frontend/users/read
  header('Location: /');
  return;
}

if ($isCookied) {
  //index properties
  $post = new Post($db);
  $post->identify = $_COOKIE['identify'];
  $post->hash = $_COOKIE['hash'];
  $isIdentify = $post->identify();
}

//Is not identify user
if (!$isIdentify) {
  //DECLARE FORM VARIABLES
  header('Location: /');
  return;
}

//Is superuser needed
if ($isIdentify) {
  //SUPERUSER PROCESS
  $isSuperUser = $post->is_super_user();
}

//is_super_user process
if (!$isSuperUser) {
  header('Location: /');
  return;
}

//read users
$result = $post->read();

//get the row count
$num = $result->rowCount();

if($num > 0) {
  $post_arr = array();
  $post_arr['data'] = array();

  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $post_item = array(
      'id' => $id,
      'rol' => $rol,
      'name' => $name,
      'softDelete' => $softDelete,
      'createdAt' => $createdAt
    );
    array_push($post_arr['data'], $post_item);
  }

  $smarty = new smarty();
  $smarty->assign('users', $post_arr['data']);
  $smarty->assign('message', $message);
  $smarty->display("templates/{$_REQUEST['page']}.tpl");
}
else {
  $smarty = new smarty();
  $smarty->assign('users', '');
  $smarty->assign('message', 'Ocurrió algún error');
  $smarty->display("templates/{$_REQUEST['page']}.tpl");
}

?>
